<template>
	<div class="lists-container point-lists-container">
    <div class="order-wrapper" v-if="listsData.length>0">      
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        :immediate-check="false"
        error-text="请求失败，点击重新加载"
        finished-text=""
        @load="onLoad"
      >
        <div class="order-box" v-for="(listsItem,index) in listsData" :key="index">
          <section class="order-list-info clearfix">
            <a href=”javascript:;“>
              <span class="fl">
                <p>订单：{{listsItem.order_no}}</p>
                <p>日期：{{listsItem.create_time}}</p>
              </span>
              <span class="status fr">{{listsItem.status_name}}</span>
            </a>
          </section>
          <section class="order-goods">
            <ul>
              <li v-for="(goods,index) in listsItem.goods" :key="index" class="goods-li">
                <section class="order-goods-img">
                  <a href="javascript:;" @click="JumpName('exchangeDetail',{id:goods.point_exchange_id})">
                    <img :src="goods.pic_url+'80x80'" width="80" height="80" v-if="goods.is_compress"/>
                    <img :src="goods.pic_url" width="80" height="80" v-else/>
                  </a>
                </section>
                <section class="order-goods-infor">
                  <!-- <a class="goods-title" href="">{{listsItem.title}}</a>
                  <p class="goods-props" v-if="listsItem.props">{{listsItem.props}}</p>
                  <section class="goods-price-num fontGilroy clearfix">
                    <p class="price fl">兑换{{point_name}}：<em class="fontGilroy">{{listsItem.point}}</em></p>
                    <span class="num fr"><i>x</i>{{listsItem.num}}</span>
                  </section> -->
                  <div class="left">
                    <a class="goods-title" href="javascript:;">{{goods.title}}</a>
                    <p class="goods-props" v-if="goods.props">{{goods.props}}</p>
                    <p class="price goods-point">兑换{{point_name}}：{{goods.point}}</p>
                  </div>
                  <div class="right">
                    <span class="num fr"><i>x</i>{{goods.num}}</span>
                  </div>
                </section>
              </li>
            </ul>
          </section>

          <section class="order-pay">
            <div class="good-more-btn">
              <span class="total-points">兑换总{{point_name}}：<span class="point-num fontGilroy">{{listsItem.points}}</span></span>
              <span v-if="listsItem.status==0">
                <span class="balance" v-if="listsItem.balance_fee!=0">使用余额：{{mSymbol.name}}{{listsItem.balance_fee}}<br/></span>
                <!-- <a href="javascript:;" class="J_pay orange-btn" data-hantePay="{$is_han_te_pay}">付款</a> -->
                <van-button round hairline class="btn point-pay-btn" href="javascript:;" @click="clickPay(listsItem)">付款</van-button>
              </span>
              <van-button round hairline class="btn orange-btn"  v-if="listsItem.status==0 || listsItem.status==3 || listsItem.status==4 || listsItem.status==5" @click="clickDelOrder(listsItem.point_exchange_order_id)">删除订单</van-button>
              <van-button round hairline class="btn orange-btn" v-if="listsItem.status==2" @click="clickConfirm(listsItem.point_exchange_order_id)">确认收货</van-button>
              <van-button round hairline class="btn" @click="JumpName('pointOrderRefunding',{id:listsItem.point_exchange_order_id})" v-if="(listsItem.status == 1 || (listsItem.status == 2 && listsItem.is_self_take == 1)) && is_allow_return">退款</van-button>
              <!-- <van-button round hairline class="btn orange-btn" :url="'/User/order_detail/id/'+listsItem.point_exchange_order_id">详情</van-button> -->
              <van-button round hairline class="btn" @click="JumpName('pointOrderDetail',{id:listsItem.point_exchange_order_id})">详情</van-button>
            </div>
          </section>
        </div>
      </van-list>
    </div>
    <div v-else>
      <no-data :noData=noData></no-data>
    </div>
    <!-- 付款弹窗 -->
    <van-popup v-model="showPayPop" class="pay-box" position="top" :style="{ height: '100%' }">
      <!-- <tx-pop @closePop="closeCashPop" :dzData="dzData" :cashPopData="cashPopData"></tx-pop> -->
      <more-payment @closePayPop="closePayPop" :isTlfzPay="isTlfzPay" :isHffzPay="true" @payCallback="payCallback" :payPopData="payPopData"></more-payment>
    </van-popup>  
  </div>
</template>

<script>
import { Dialog } from 'vant'
import { getPointOrderInfo, getPointOrderList, delPointOrder, pointPayUrl, pointOrderConfirm } from '@/api/user/member/memberApi'
import MorePayment from '@/components/MorePayment/index'
import PayPassword from '@/components/PayPassword/index'
import noData from '@/components/noData/index'
// import noOrderImg from '@img/no_order.png'
import small from '@/smallapp/small'
import { mapGetters } from 'vuex'
import Vue from 'vue'
export default Vue.extend({
  name: 'index',
  components: {
    noData,
    MorePayment,
    PayPassword
  },
  props: {
    curType: {
      type: Number,
      default: '1'
    }
  },
  data() {
    return {
      noData: {
        img: 'https://img.wifenxiao.com/h5-wfx/images/no_order.png',
        text: '暂无积分商品订单',
        marginTop: '60px',
        width: '214px',
        txtMarginTop: '-46px'
      },
      must_pay_password: false, // 强制设置支付密码
      popup_show: '',
      showPayPop: false, // 付款弹窗
      showPwd: false, // 支付密码弹框是否显示
      is_alipay: null,
      is_wx_pay: null,
      is_cod: null,
      is_bank: null,
      is_paypal: null,
      is_beibao: null,
      is_offline: null,
      is_hantePay: null,
      payPopData: {

      },
      submitData: {},
      point_name: '积分',
      code: '',
      listsData: [],
      loading: false,
      finished: false,
      error: false,
      p: 1,
      isTlfzPay: false,
      remark: -1,
      is_allow_return: 0
    }
  },
  methods: {
    JumpName(url, data) {
      this.$JumpName(this, url, data)
    },
    Jump(url, data) {
      this.$JumpPath(this, url, data)
    },
    getPointOrder(type) {
      this.finished = false
      this.p = 1
      this.listsData = []
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      getPointOrderInfo().then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const resData = res.data
          this.point_name = resData.point_name
          const pageTitle = resData.point_name + '兑换商品订单'
            wx.setNavigationBarTitle({
              title: pageTitle
            })
          this.code = resData.code
          this.must_pay_password = resData.must_pay_password || false
          this.popup_show = resData.popup_show
          this.is_allow_return = resData.is_allow_return
          // 付款弹窗信息
          this.payPopData.balance = resData.balance
          this.payPopData.is_dhs_allow_deposit = resData.is_dhs_allow_deposit
          this.payPopData.is_check_dhs = resData.is_check_dhs
          this.payPopData.dhs_deposit = resData.dhs_deposit
          this.payPopData.deposit_alias = resData.deposit_alias
          this.payPopData.default_pay_type = resData.default_pay_type // 默认付款方式
          this.payPopData.default_pay = resData.default_pay // hantePay默认付款方式
          this.payPopData.is_open_balance_pay = resData.is_open_balance_pay // 是否开启余额支付
          this.payPopData.tlfz_point_exchange = resData.tlfz_point_exchange == 1
          this.isTlfzPay = resData.tlfz_point_exchange == 1
          this.is_alipay = resData.is_alipay
          this.is_wx_pay = resData.is_wx_pay
          this.is_cod = resData.is_cod
          this.is_bank = resData.is_bank
          this.is_paypal = resData.is_paypal
          this.is_beibao = resData.is_beibao
          this.is_offline = resData.is_offline || 0
          this.is_han_te_pay = resData.is_han_te_pay
        } else {
          this.$Error(res.msg)
        }
      })

      const params = {
        status: type,
        p: 1
      }
      this.finished = false
      this.loading = false
      getPointOrderList(params).then(res => {
        if (res.status == 1) {
          const resData = res.data
          let listArr = ''
          if (this.curType == 1 || !this.curType) {
            listArr = resData.lists
          } else if (this.curType == 2) {
            listArr = resData.wait_lists
          } else if (this.curType == 3) {
            listArr = resData.send_lists
          } else if (this.curType == 4) {
            listArr = resData.complain_lists
          }
          // console.log(listArr)
          // this.listsData.push(...listArr)
          this.listsData = listArr
          this.p++
        } else {
          this.$Error(res.msg)
        }
      })
    },
    onLoad() {
      this.loading = true
      const params = {
        status: this.curType,
        p: this.p
      }
      getPointOrderList(params)
        .then(res => {
          this.loading = false
          const resData = res.data
          let listArr = ''
          if (this.curType == 1 || !this.curType) {
            listArr = resData.lists
          } else if (this.curType == 2) {
            listArr = resData.wait_lists
          } else if (this.curType == 3) {
            listArr = resData.send_lists
          }
          if (listArr.length) {
            this.listsData.push(...listArr)
            this.p++
          } else {
            this.finished = true
          }
        })
        .catch(() => {
          this.error = true
        })
    },
    // 删除订单
    clickDelOrder(id) {
      Dialog.confirm({
        message: '确定删除？',
        className: 'common-confirm',
        closeOnClickOverlay: true
      }).then(() => {
        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
        const params = {
          id: id,
          code: this.code
        }
        delPointOrder(params).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.$Error('操作成功')
            this.getPointOrder()
          } else {
            this.$Error(res.msg)
          }
        })
        // on confirm
      }).catch(() => {
        // on cancel
      })
    },

    // 确认收货
    clickConfirm(id) {
      pointOrderConfirm({ id: id }).then(res => {
        if (res.status == 1) {
          this.$Error('操作成功')
          this.getPointOrder()
        } else {
          this.$Error(res.msg)
        }
      })
    },

    // 点击付款
    clickPay(item) {
      // if (!is_alipay && !is_wx_pay && !is_cod && !is_bank && !is_paypal && !is_beibao && !is_offline && !is_hantePay) {
      /* if (!(this.is_alipay == 1 || this.is_wx_pay == 1 || this.is_cod == 1 || this.is_bank == 1 || this.is_paypal == 1 || this.is_beibao == 1 || this.is_offline == 1 || this.is_han_te_pay == 1)) {
        this.$Error('抱歉，暂时不能付款！')
        return false
      } */
      /* const payType = item.pay_type
      const peerType = item.peer_type
      // 全部订单列表代码
      if (payType == 5) {
        window.location.href = '/Paypal/doPaypal/order_id/' + item.point_exchange_order_id
        return false
      } else if (payType == 7 && peerType == 2) {
        window.location.href = '/PeerPay/peer_detail/id/' + item.point_exchange_order_id
        return false
      } */
      this.payPopData.payment = item.post_fee
      this.payPopData.order_id = item.point_exchange_order_id

      this.showPayPop = true
    },

    // 关闭付款弹窗
    closePayPop() {
      this.showPayPop = false
    },
    // 点击确定付款，付款请求
    payCallback(submitData) {
      // console.log(submitData)
      this.submitData = submitData
      // var payType = $('input[name="type"]:checked').val()
      const payType = submitData.type
      const order_id = submitData.order_id
      const money_type = submitData.moneyType
      // var money_type = $('input[name="money_type"]:checked').val()
      const popup_show = this.popup_show
      // var popup_show = $('#popup_show').val()
      // const balance = this.payPopData.balance
      const payment = this.payPopData.payment
      // var sumPrice = $('.balance_money').text()
      // const must_pay_password = this.must_pay_password
      // var must_pay_password = $(':hidden[name="must_pay_password"]').val()
      const global_alipay_currency = submitData.global_alipay_currency
      // var global_alipay_currency = $('[name=global_alipay_currency]').val()
      // // console.log(must_pay_password);
      const hantepay = submitData.hantepay
      // var hantepay = $('[name=hantepay]:checked').val()// 定制HantePay
      // 通联分账
      const tlfz_pay_type = submitData.tlfz_pay_type
      const payment_type = submitData.payment_type

      // 是否强制使用支付密码
      if (this.must_pay_password == 1) {
        if (money_type == 2 && payment > 0) {
          this.$Error('请先去会员中心的修改资料里设置支付密码!')
        } else {
          const params = { hantepay: hantepay, global_alipay_currency: global_alipay_currency, pay_type: payType, order_id: order_id, money_type: money_type, tlfz_pay_type, payment_type }
          if (payType == 34) {
            params.adapay_pay_type = submitData.adapay_pay_type
          }
          this.$loadingWrap.show()
          setTimeout(() => {
            this.$loadingWrap.close()
          }, 10000)
          pointPayUrl(params).then(res => {
            this.$loadingWrap.close()
            if (res.status == 1) {
              // window.location.href = res.url
              // TODO 小程序支付
              if(this.submitData.type == 2 && res.data.jsApiParameters){
                const payData = JSON.parse(res.data.jsApiParameters)
                wx.requestPayment({
                  timeStamp: payData.timeStamp,
                  nonceStr: payData.nonceStr, //
                  package: payData.package, //
                  signType: payData.signType, //微信签名方式
                  paySign: payData.paySign, //微信签名
                  success: (res) => {
                    // console.log(res)
                    this.getPointOrder(this.curType)
                    this.closePayPop()
                  },
                  fail: (failmsg) => {
                    // console.log(failmsg)
                  }
                })
              } else if (this.submitData.type == 26 && res.data.is_mini_vsp) {
                this.Jump('/buyTonglianWait',{ order_id, pay_type: 3 })
              } else if (this.submitData.type == 34 && res.data.jsApiParameters) {
                if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
                  const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
                  this.hfAppId = jsApiParameters.wx_app_id
                  const that = this
                  wx.navigateToMiniProgram({
                    appId: jsApiParameters.wx_app_id,
                    path: jsApiParameters.miniapp_path,
                    success(res) {
                      // 打开成功
                      // console.log(res)
                    },
                    fail(error) {
                      that.closePayPop()
                      that.remark = -1
                    }
                  })
                } else if (small.wxCache('adapayPlugVersion') == 'self') {
                  const payData = JSON.parse(res.data.jsApiParameters)
                  wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr, //
                    package: payData.package, //
                    signType: payData.signType, //微信签名方式
                    paySign: payData.paySign, //微信签名
                    success: (res) => {
                      // console.log(res)
                      this.getPointOrder(this.curType)
                      this.closePayPop()
                    },
                    fail: (failmsg) => {
                      // console.log(failmsg)
                    }
                  })
                } else {
                  const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
                  // 汇付分账
                  this.isSubmit = false
                  // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
                  const hfPay= res.data.jsApiParameters
                  if (hfPay) {
                    adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
                  }
                }
              } else {
                setTimeout(() => {
                  this.getPointOrder(this.curType)
                }, 1000)
                this.closePayPop()
              }
            } else {
              this.$Error(res.msg)
            }
          })
        }
      } else {
        if (money_type == 2 && popup_show) {
          this.showPwd = true
        } else {
          const params = { hantepay: hantepay, global_alipay_currency: global_alipay_currency, pay_type: payType, order_id: order_id, money_type: money_type, tlfz_pay_type, payment_type }
          if (payType == 34) {
            params.adapay_pay_type = submitData.adapay_pay_type
          }
          this.$loadingWrap.show()
          setTimeout(() => {
            this.$loadingWrap.close()
          }, 10000)
          pointPayUrl(params).then(res => {
            this.$loadingWrap.close()
            if (res.status == 1) {
              // window.location.href = res.url
              // TODO 小程序支付
              if(this.submitData.type == 2 && res.data.jsApiParameters){
                const payData = JSON.parse(res.data.jsApiParameters)
                wx.requestPayment({
                  timeStamp: payData.timeStamp,
                  nonceStr: payData.nonceStr, //
                  package: payData.package, //
                  signType: payData.signType, //微信签名方式
                  paySign: payData.paySign, //微信签名
                  success: (res) => {
                    // console.log(res)
                    this.getPointOrder(this.curType)
                    this.closePayPop()
                  },
                  fail: (failmsg) => {
                    // console.log(failmsg)
                  }
                })
              } else if (this.submitData.type == 26 && res.data.is_mini_vsp) {
                this.Jump('/buyTonglianWait',{ order_id, pay_type: 3 })
              } else if (this.submitData.type == 34 && res.data.jsApiParameters) {
                if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
                  const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
                  this.hfAppId = jsApiParameters.wx_app_id
                  const that = this
                  wx.navigateToMiniProgram({
                    appId: jsApiParameters.wx_app_id,
                    path: jsApiParameters.miniapp_path,
                    success(res) {
                      // 打开成功
                      // console.log(res)
                    },
                    fail(error) {
                      that.closePayPop()
                      that.remark = -1
                    }
                  })
                } else if (small.wxCache('adapayPlugVersion') == 'self') {
                  const payData = JSON.parse(res.data.jsApiParameters)
                  wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr, //
                    package: payData.package, //
                    signType: payData.signType, //微信签名方式
                    paySign: payData.paySign, //微信签名
                    success: (res) => {
                      // console.log(res)
                      this.getPointOrder(this.curType)
                      this.closePayPop()
                    },
                    fail: (failmsg) => {
                      // console.log(failmsg)
                    }
                  })
                } else {
                  const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
                  // 汇付分账
                  this.isSubmit = false
                  // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
                  const hfPay= res.data.jsApiParameters
                  if (hfPay) {
                    adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
                  }
                }
              } else {
                setTimeout(() => {
                  this.getPointOrder(this.curType)
                }, 1000)
                this.closePayPop()
              }
            } else {
              this.$Error(res.msg)
            }
          })
        }
      }
    },
    // 输入支付密码点击确定
    payPwdCallback() {
      const submitData = this.submitData
      // var payType = $('input[name="type"]:checked').val()
      const payType = submitData.type
      const order_id = submitData.order_id
      const money_type = submitData.moneyType
      // var money_type = $('input[name="money_type"]:checked').val()
      // var popup_show = $('#popup_show').val()
      // const balance = this.payPopData.balance
      // var sumPrice = $('.balance_money').text()
      // const must_pay_password = this.must_pay_password
      // var must_pay_password = $(':hidden[name="must_pay_password"]').val()
      const global_alipay_currency = submitData.global_alipay_currency
      // var global_alipay_currency = $('[name=global_alipay_currency]').val()
      // // console.log(must_pay_password);
      const hantepay = submitData.hantepay
      const params = { hantepay: hantepay, global_alipay_currency: global_alipay_currency, pay_type: payType, order_id: order_id, money_type: money_type }
      if (payType == 34) {
        params.adapay_pay_type = submitData.adapay_pay_type
      }
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      pointPayUrl(params).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          // window.location.href = res.url
          // TODO 小程序支付
          if(this.submitData.type == 2 && res.data.jsApiParameters){
            const payData = JSON.parse(res.data.jsApiParameters)
            wx.requestPayment({
              timeStamp: payData.timeStamp,
              nonceStr: payData.nonceStr, //
              package: payData.package, //
              signType: payData.signType, //微信签名方式
              paySign: payData.paySign, //微信签名
              success: (res) => {
                // console.log(res)
                this.getPointOrder(this.curType)
                this.closePayPop()
              },
              fail: (failmsg) => {
                // console.log(failmsg)
              }
            })
          } else if (this.submitData.type == 26 && res.data.is_mini_vsp) {
            this.Jump('/buyTonglianWait',{ order_id, pay_type: 3 })
          } else if (this.submitData.type == 34 && res.data.jsApiParameters) {
            if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
              const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
              this.hfAppId = jsApiParameters.wx_app_id
              const that = this
              wx.navigateToMiniProgram({
                appId: jsApiParameters.wx_app_id,
                path: jsApiParameters.miniapp_path,
                success(res) {
                  // 打开成功
                  // console.log(res)
                },
                fail(error) {
                  that.closePayPop()
                  that.remark = -1
                }
              })
            } else if (small.wxCache('adapayPlugVersion') == 'self') {
              const payData = JSON.parse(res.data.jsApiParameters)
              wx.requestPayment({
                timeStamp: payData.timeStamp,
                nonceStr: payData.nonceStr, //
                package: payData.package, //
                signType: payData.signType, //微信签名方式
                paySign: payData.paySign, //微信签名
                success: (res) => {
                  // console.log(res)
                  this.getPointOrder(this.curType)
                  this.closePayPop()
                },
                fail: (failmsg) => {
                  // console.log(failmsg)
                }
              })
            } else {
              const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
              // 汇付分账
              this.isSubmit = false
              // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
              const hfPay= res.data.jsApiParameters
              if (hfPay) {
                adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
              }
            }
          } else{
            setTimeout(() => {
              this.getPointOrder(this.curType)
            }, 1000)
            this.closePayPop()
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 关闭输入支付密码弹窗
    closePwd() {
      this.showPwd = false
    }
  },
  created() {
    if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
      this.remark = 1
    }
    this.getPointOrder(this.curType)
  },
  mounted() {
    // 小程序触底加载更多
    window.addEventListener('reachbottom', () => {
      // console.log('reachbottom')
      /* if(this.finished){
        return false
      } */
      this.onLoad()
    })
    if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
      window.addEventListener('wxshow', () => {
        let options = wx.getEnterOptionsSync();
        // wx1e18d140f890f2c5，wx308088053f4ecc3a
        if (options.scene == '1038' && options.referrerInfo.appId == this.hfAppId && this.remark == 2) {
          this.closePayPop()
          // 代表从收银台小程序返回
          // this.Jump('/order-lists')
          this.remark = -1
          window.location.reload()
        }
      }),
      window.addEventListener('wxHide', () => {
        this.remark = 2
      })
    }
  },
  watch: {
    curType(val) {
      this.getPointOrder(this.curType)
      // window.scroll(0, 0)
    }
  },
  computed: {
    // 获取自定义符号
    ...mapGetters(['mSymbol'])
  }
})
</script>

<style lang="scss">
@import "src/styles/order/lists";
.lists-container{
  &.point-lists-container{
    .goods-point{
      font-size:28px;
      color:#F42B2B;
    }
    .good-more-btn{
      .balance{
        margin-left:8px;
        color:#FF8C01;
      }
      .btn{
        &.point-pay-btn{
          border-color:#FF8C01;
          color:#FF8C01;
        }
      }
    }
  }
}
</style>